﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using WordService.Business.IBLL;
using WordService.Business;
using WordService.Model;

namespace WordLib.ProcessUI
{
    public partial class CalSettingsPanel : UserControl
    {
        public CalSettingsPanel()
        {
            InitializeComponent();
            LoadForm();
        }

        private IAuthorBLL authorBLL = BLLManager.CreateAuthorBLL();
        private IKeywordBLL keywordBLL = BLLManager.CreateKeywordBLL();
        // 全局变量

        // 源数据作者和关键字的Mapping
        private IDictionary<String, IList<Author>> sourceAuthors = new Dictionary<String, IList<Author>>();
        private IDictionary<String, IList<Keyword>> sourceKeyword = new Dictionary<String, IList<Keyword>>();
        // 作者所写的所有文章ID号
        private IDictionary<String, IList<Int64>> selectAuthors = new Dictionary<String, IList<Int64>>();
        // 目标数据作者、关键字
        // private IDictionary<String, IList<Author>> targetAuthors = new Dictionary<String, IList<Author>>();
        // 关键字的键为Category的值
        private IDictionary<String, KeywordGrid> targetKeyword = new Dictionary<String, KeywordGrid>();
        private IDictionary<String, AuthorGrid> targetAuthors = new Dictionary<String, AuthorGrid>();
        private IList<String> categories = new List<String>();
        // 关键字的DataSource
        private IList<KeywordGrid> keywordDataSource = new List<KeywordGrid>();

        private void ResetData()
        {
            if (sourceAuthors != null)
            {
                sourceAuthors.Clear();
            }
            if (sourceKeyword != null)
            {
                sourceKeyword.Clear();
            }
            if (targetAuthors != null)
            {
                targetAuthors.Clear();
            }
            if (targetKeyword != null)
            {
                targetKeyword.Clear();
            }
            if (categories != null)
            {
                categories.Clear();
            }
            if (keywordDataSource != null)
            {
                keywordDataSource.Clear();
            }
        }

        private void LoadForm()
        {
            ResetData();
            // 初始化所有的内容
            {
                if (this.cbxAuthor != null)
                {
                    this.cbxAuthor.Items.Clear();
                }
                if (this.cbxKeyword != null)
                {
                    this.cbxKeyword.Items.Clear();
                }
            }
            // 作者下拉填充
            IList<Author> authors = authorBLL.QueryAllAuthors();
            IList<Keyword> keywords = keywordBLL.QueryAllKeywords();
            // 填充作者下拉
            foreach (Author author in authors)
            {
                if (this.sourceAuthors.ContainsKey(author.Name))
                {
                    this.sourceAuthors[author.Name].Add(author);
                }
                else
                {
                    IList<Author> authorList = new List<Author>();
                    this.sourceAuthors.Add(author.Name, authorList);
                    authorList.Add(author);
                    this.cbxAuthor.Items.Add(author.Name);
                }
            }
            // 填充关键字下拉
            foreach (Keyword keyword in keywords)
            {
                if (this.sourceKeyword.ContainsKey(keyword.Name))
                {
                    this.sourceKeyword[keyword.Name].Add(keyword);
                }
                else
                {
                    IList<Keyword> keywordList = new List<Keyword>();
                    this.sourceKeyword.Add(keyword.Name, keywordList);
                    keywordList.Add(keyword);
                    this.cbxKeyword.Items.Add(keyword.Name);
                }
            }
            // 添加右键
            this.lbCategories.ContextMenuStrip = cmsCategories;
            this.dgvKeywords.ContextMenuStrip = cmsKeyword;
            this.dgvAuthors.ContextMenuStrip = cmsAuthor;
        }

        private void btnCategory_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.txtCategory.Text))
            {
                MessageBox.Show(this, "请输入你要填写的类别名称！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                if (this.categories.Contains(this.txtCategory.Text))
                {
                    MessageBox.Show(this, "对不起，你输入的类别名称已经存在！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    this.categories.Add(this.txtCategory.Text);
                    this.lbCategories.Items.Add(this.txtCategory.Text);
                    this.cbxKeywordCat.Items.Add(this.txtCategory.Text);
                    this.txtCategory.Text = String.Empty;
                }
            }
        }

        private void lbCategories_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && this.lbCategories.SelectedIndex != -1)
            {
                cmsCategories.Show(MousePosition);
                this.cbxKeywordCat.SelectedIndex = -1;
                this.cbxKeyword.SelectedIndex = -1;
            }
        }

        private void DelCategoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.lbCategories.SelectedIndex != -1)
            {
                int index = this.lbCategories.SelectedIndex;
                String removeCat = this.lbCategories.Items[index].ToString();
                {
                    this.dgvKeywords.DataSource = null;
                    this.dgvKeywords.Update();
                    this.keywordDataSource = GetRemovedSource(removeCat);
                    this.dgvKeywords.DataSource = this.keywordDataSource;
                    this.dgvKeywords.Update();
                }
                this.lbCategories.Items.RemoveAt(index);
                this.cbxKeywordCat.Items.RemoveAt(index);
                this.categories.RemoveAt(index);
                MessageBox.Show(this, "您选择的类别已经成功删除！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show(this, "对不起，请选择您要删除的类别！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        // 添加作者
        private void btnAuthor_Click(object sender, EventArgs e)
        {
            if (ValidateAuthor())
            {
                if (this.lbCategories.Items.Count == 0)
                {
                    MessageBox.Show(this, "对不起，请先添加类别，再添加作者！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                String selectAuthor = this.cbxAuthor.Items[this.cbxAuthor.SelectedIndex].ToString();
                if (this.targetAuthors.ContainsKey(selectAuthor))
                {
                    MessageBox.Show(this, "对不起，该作者已经添加！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    if (sourceAuthors.ContainsKey(selectAuthor))
                    {
                        AuthorGrid grid = new AuthorGrid(selectAuthor);
                        this.targetAuthors.Add(selectAuthor, grid);
                        IList<AuthorGrid> authorDataSource = new List<AuthorGrid>();
                        // 填充选择的作者
                        IList<Int64> articleIds = GetArticleId(selectAuthor);
                        if (!selectAuthors.ContainsKey(selectAuthor))
                        {
                            selectAuthors.Add(selectAuthor, articleIds);
                        }
                        foreach (String author in selectAuthors.Keys)
                        {
                            authorDataSource.Add(this.targetAuthors[author]);
                        }
                        this.dgvAuthors.DataSource = authorDataSource;
                        this.dgvAuthors.Update();
                        this.cbxAuthor.SelectedIndex = -1;
                    }
                }
            }
        }
        // 添加关键字
        private void btnKeyword_Click(object sender, EventArgs e)
        {
            if (ValidateKeyword())
            {
                // 填充TargetKeyword
                String selectCategory = this.cbxKeywordCat.Items[this.cbxKeywordCat.SelectedIndex].ToString();
                String selectKeyword = this.cbxKeyword.Items[this.cbxKeyword.SelectedIndex].ToString();
                if (this.targetKeyword.ContainsKey(selectKeyword))
                {
                    MessageBox.Show(this, "对不起，一个关键字只能添加到一个类别里！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    KeywordGrid grid = new KeywordGrid(selectKeyword, selectCategory);
                    this.targetKeyword.Add(selectKeyword, grid);
                    keywordDataSource = new List<KeywordGrid>();
                    foreach (KeywordGrid keyword in this.targetKeyword.Values)
                    {
                        keywordDataSource.Add(keyword);
                    }
                    this.dgvKeywords.DataSource = keywordDataSource;
                    this.dgvKeywords.Update();
                    this.cbxKeyword.SelectedIndex = -1;
                    this.cbxKeywordCat.SelectedIndex = -1;
                }
            }
        }

        private IList<Int64> GetArticleId(String selectName)
        {
            IList<Int64> resultIds = new List<Int64>();
            IList<Author> authors = this.sourceAuthors[selectName];
            foreach (Author author in authors)
            {
                if (author.Article != null && !resultIds.Contains(author.Article.ID))
                {
                    resultIds.Add(author.Article.ID);
                }
            }
            return resultIds;
        }

        private IList<AuthorGrid> GetRemovedAuthor(String userName)
        {
            IList<AuthorGrid> newSource = new List<AuthorGrid>();
            foreach (AuthorGrid grid in this.targetAuthors.Values)
            {
                if (!grid.UserName.Trim().Equals(userName))
                {
                    newSource.Add(grid);
                }
                else
                {
                    this.targetAuthors.Remove(grid.UserName);
                }
            }
            return newSource;
        }

        private IList<KeywordGrid> GetRemovedSource(String category)
        {
            IList<KeywordGrid> newSource = new List<KeywordGrid>();
            foreach (KeywordGrid grid in this.keywordDataSource)
            {
                if (!grid.Category.Trim().Equals(category))
                {
                    newSource.Add(grid);
                }
                else
                {
                    targetKeyword.Remove(grid.Keyword);
                }
            }
            return newSource;
        }

        private Boolean ValidateAuthor()
        {
            if (this.cbxAuthor.SelectedIndex == -1)
            {
                MessageBox.Show(this, "对不起，请选择您要添加的作者！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }

        private Boolean ValidateKeyword()
        {
            if (this.cbxKeyword.SelectedIndex == -1)
            {
                MessageBox.Show(this, "对不起，请选择您要添加的关键字！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (this.cbxKeywordCat.Items.Count == 0)
            {
                MessageBox.Show(this, "对不起，因为系统里面没有任何类别信息，请先添加类别信息！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (this.cbxKeywordCat.SelectedIndex == -1)
            {
                MessageBox.Show(this, "对不起，请选择您添加的关键字所属的类别！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }

        private void DelAuthorRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dgvAuthors.CurrentRow == null)
            {
                MessageBox.Show(this, "对不起，请选择您要删除的作者！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            String removeKey = (this.dgvAuthors.CurrentRow.Cells["UserName"].Value.ToString());
            int removeIndex = this.dgvAuthors.CurrentRow.Index;
            if (removeIndex != -1)
            {
                {
                    // 先重置DataSource
                    this.dgvAuthors.DataSource = null;
                    this.dgvAuthors.Update();
                    // 改变数据源内容
                    this.selectAuthors.Remove(removeKey);
                    this.targetAuthors.Remove(removeKey);
                    // 选择的作者
                    IList<AuthorGrid> authorDataSource = new List<AuthorGrid>();
                    foreach (AuthorGrid author in this.targetAuthors.Values)
                    {
                        // 填充选择的作者
                        authorDataSource.Add(author);
                    }
                    // 重新赋值
                    this.dgvAuthors.DataSource = authorDataSource;
                    this.dgvAuthors.Update();
                }
            }
        }

        private void DelKeywordRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dgvKeywords.CurrentRow == null)
            {
                MessageBox.Show(this, "对不起，请选择您要删除的关键字！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            String removeKey = (this.dgvKeywords.CurrentRow.Cells["Keyword"].Value.ToString());
            int removeIndex = this.dgvKeywords.CurrentRow.Index;
            if (removeIndex != -1)
            {
                {
                    // 先将DataGridView的内容重置
                    this.dgvKeywords.DataSource = null;
                    this.dgvKeywords.Update();
                    // 改变数据源的内容
                    this.keywordDataSource.RemoveAt(removeIndex);
                    this.targetKeyword.Remove(removeKey);
                    // 重新为DataGridView赋值
                    this.dgvKeywords.DataSource = this.keywordDataSource;
                    this.dgvKeywords.Update();
                }
            }
        }

        private void dgvKeywords_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex > 0 && e.ColumnIndex > 0)
                {
                    cmsKeyword.Show(MousePosition);
                    this.cbxKeywordCat.SelectedIndex = -1;
                    this.cbxKeyword.SelectedIndex = -1;
                }
            }
        }

        private void dgvAuthors_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex > 0 && e.ColumnIndex > 0)
                {
                    cmsAuthor.Show(MousePosition);
                    this.cbxAuthor.SelectedIndex = -1;
                }
            }
        }

        #region 开放的API，用来获取数据用的
        public IDictionary<String, IList<Keyword>> GetKeywordSource()
        {
            return this.sourceKeyword;
        }
        public IDictionary<String, KeywordGrid> GetSelectKeywordSource()
        {
            return this.targetKeyword;
        }

        public IDictionary<String, IList<Int64>> GetSelectAuthors()
        {
            return this.selectAuthors;
        }
        #endregion

    }
}